package network;

import com.jme3.network.ConnectionListener;
import com.jme3.network.HostedConnection;
import com.jme3.network.Message;
import com.jme3.network.MessageListener;
import com.jme3.network.Server;

public class ServerListener implements ConnectionListener, MessageListener<HostedConnection> {

    public void connectionAdded(Server server, HostedConnection conn) {
	System.out.println("Client "+conn.getId()+" connected from "+conn.getAddress());
    }

    public void connectionRemoved(Server server, HostedConnection conn) {
	System.out.println("Client "+conn.getId()+" disconnected.");
	server.broadcast(new StringMessage(((PlayerInfo)conn.getAttribute(NetworkUtil.CONNECTION_PLAYER_INFO)).getPlayerName()+" disconnected."));
    }

    public void messageReceived(HostedConnection source, Message message) {
	if(message instanceof PlayerInfo) {
	    source.setAttribute(NetworkUtil.CONNECTION_PLAYER_INFO, (PlayerInfo)message);
	    source.getServer().broadcast(new StringMessage(((PlayerInfo)message).getPlayerName()+" connected."));
	}
    }
}
